package com.jsz.yun.ai.field.repository.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jsz.yun.ai.field.entity.UserEntity;
import com.jsz.yun.ai.field.enums.ResultCodeEnum;
import com.jsz.yun.ai.field.exception.BusinessException;
import com.jsz.yun.ai.field.mapper.UserInfoMapper;
import com.jsz.yun.ai.field.po.UserInfoPO;
import com.jsz.yun.ai.field.repository.UserInfoRepository;
import com.jsz.yun.ai.field.repository.assembler.UserInfoAssembler;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;


/**
 * @author gaoxing
 * @date 2025-03-25 09:23:30
 */
@Service
public class UserInfoRepositoryImpl implements UserInfoRepository {

    @Resource
    UserInfoMapper userInfoMapper;

    @Resource
    UserInfoAssembler userInfoAssembler;

    @Override
    public UserEntity creatUser(UserEntity user) {
        user.setUserId(UUID.randomUUID().toString());
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        UserInfoPO userInfo = userInfoAssembler.toUserInfoPo(user);
        int insert = userInfoMapper.insert(userInfo);
        if (insert > 0){
            return user;
        }
        throw new BusinessException(ResultCodeEnum.CREATE_USER_FAIL);
    }

    @Override
    public UserEntity selectUser(UserEntity user) {
        QueryWrapper<UserInfoPO> wrapper = new QueryWrapper<>();
        wrapper.eq("phone_number", user.getPhoneNumber());
        UserInfoPO userInfo = userInfoMapper.selectOne(wrapper);
        return  userInfoAssembler.toUserInfoEntity(userInfo);
    }

    @Override
    public UserEntity validateUser(UserEntity userEntity) {
        QueryWrapper<UserInfoPO> wrapper = new QueryWrapper<>();
        wrapper.eq("phone_number", userEntity.getPhoneNumber());
        wrapper.eq("password", userEntity.getPassword());
        UserInfoPO userInfo = userInfoMapper.selectOne(wrapper);
        if (ObjUtil.isEmpty(userInfo)) {
            throw new BusinessException(ResultCodeEnum.USER_IS_NULL);
        }
        return  userInfoAssembler.toUserInfoEntity(userInfo);
    }

    @Override
    public UserEntity selectUserById(String userId) {
        QueryWrapper<UserInfoPO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        UserInfoPO userInfo = userInfoMapper.selectOne(wrapper);
        return  userInfoAssembler.toUserInfoEntity(userInfo);
    }
}
